<?php
declare (strict_types=1);

namespace app\middleware;

use app\common\library\Response as LibResponse;
use app\common\service\AdminUserService;
use app\common\service\AdminVisitLogService;
use think\facade\View;
use think\Response;

class AdminLogin
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //检测登录状态
        $user_info = AdminUserService::ins()->checkLogin();
        if (!$user_info) { //跳转登录
            return redirect('/admin/pub/login');
        }
        $request->user_info = $user_info;
        //检测用户的权限
        $url = menu_url();
        if (!in_array($url, config('app.admin_common_menu'))) { //入口菜单不检查权限
            $user_auth = check_auth($url, $user_info['role_id']);
            if (!$user_auth) {
                if ($request->isAjax()) {
                    return (new LibResponse())->error('您没有该菜单的访问权限')->getResult();
                }
                View::assign('data', ['code' => 0, 'msg' => '您没有该菜单的访问权限']);
                return Response::create('../tpl/dispatch_jump.html', 'view');
            }
        }
        //记录访问日志
        (new AdminVisitLogService())->recordLog($user_info['uid']);
        return $next($request);
    }

}
